package com.compass.doctor.ui.mine

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.widget.TextView
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.compass.doctor.R
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.callback.OnUsefulButtonClick
import com.compass.doctor.databinding.ActivityUsefulExpressionsBinding
import com.compass.doctor.dialog.USEFUL_OPT_ADD
import com.compass.doctor.dialog.USEFUL_OPT_ADD_CATE
import com.compass.doctor.dialog.UsefulExpressionsDialog
import com.compass.doctor.ui.mine.fragment.UsefulExpressionsFragment
import com.compass.doctor.ui.mine.viewmodel.UsefulExpressionsViewModel
import com.compass.framework.adapter.ViewPage2FragmentAdapter
import com.compass.framework.constant.KEY_IS_SYSTEM_USEFUL
import com.compass.framework.constant.KEY_USEFUL_CATE
import com.compass.framework.constant.REFRESH_USEFUL
import com.compass.framework.constant.REFRESH_USEFUL_CATE
import com.compass.framework.ext.onClick
import com.compass.framework.tablayout.DslTabIndicator.Companion.INDICATOR_STYLE_BOTTOM
import com.compass.framework.tablayout.DslTabIndicator.Companion.INDICATOR_STYLE_CENTER
import com.compass.framework.tablayout.DslTabIndicator.Companion.INDICATOR_STYLE_FOREGROUND
import com.compass.framework.tablayout.DslTabLayout
import com.compass.framework.utils.LiveDataBus
import com.compass.framework.utils.LogUtil
import com.compass.framework.utils.dpToPx

class UsefulExpressionsActivity : BaseVBActivity<ActivityUsefulExpressionsBinding>() {

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, UsefulExpressionsActivity::class.java)
            context.startActivity(intent)
        }
    }

    private lateinit var mViewPagerAdapter: ViewPage2FragmentAdapter
    private var mFragments: ArrayList<Fragment> = ArrayList()
    private val mUsefulExpressionsViewModel: UsefulExpressionsViewModel by viewModels()
    private var mChooseUseCateId : String? = ""
    override fun initView(savedInstanceState: Bundle?) {

        //查询常用语分组
        mUsefulExpressionsViewModel.usefulExpressionsCateListData.observe(this){
            dismissLoading()
            if (!it.isNullOrEmpty()) {
                if(mFragments.isNotEmpty()) {
                    mFragments.clear()
                    mBinding.dslTab.removeAllViews()
                }
                mBinding.dslTab.apply {

                    tabIndicator.indicatorWidth = -2
                    tabIndicator.indicatorEnableFlow = true

                    configTabLayoutConfig {
                        onSelectIndexChange = { _, selectIndexList, _, _ ->
                            val toIndex = selectIndexList.first()
                            mChooseUseCateId = it[toIndex].id
                            mBinding.viewpager2.setCurrentItem(toIndex, false)
                        }
                    }

                    for (item in it) {
                        val rxFragment = UsefulExpressionsFragment()
                        val bundleRx = Bundle()
                        bundleRx.putString(KEY_USEFUL_CATE, item.id)
                        bundleRx.putBoolean(KEY_IS_SYSTEM_USEFUL, item.isSystem)
                        rxFragment.arguments = bundleRx
                        mFragments.add(rxFragment)
                        addView(TextView(this@UsefulExpressionsActivity).apply {
                            text = item.typeName
                            textSize = 16f
                            gravity = Gravity.CENTER
                            layoutParams = DslTabLayout.LayoutParams(-2, dpToPx(48)).apply {
//                                topMargin = dpToPx(15)
                            }
                        })
                    }
                }
                initDslTab()
            }
        }

        mUsefulExpressionsViewModel.addUsefulExpressionsData.observe(this){
            dismissLoading()
            if(it){
               val pos:Int =  mBinding.viewpager2.currentItem
                val item = mUsefulExpressionsViewModel.usefulExpressionsCateListData.value?.get(pos)

               //如果添加成功，需要将当前fragment数据进行刷新
                if (item != null) {
                    LiveDataBus.get().with(REFRESH_USEFUL).postValue(item.id)
                }
            }
        }

        mBinding.llUsefulManage.onClick {
            UsefulCateExpressionsActivity.start(this@UsefulExpressionsActivity)
        }

        mBinding.llAddExpression.onClick {
            //添加常用语，直接显示常用语dialog
            if(mBinding.viewpager2.currentItem == 0){
                showToast("默认常用语不能添加")
            }else{
                UsefulExpressionsDialog.Builder(this,USEFUL_OPT_ADD,onUsefulButtonClick).show()
            }
        }

        LiveDataBus.get().with(REFRESH_USEFUL_CATE,String::class.java).observe(this){
            if(it == REFRESH_USEFUL_CATE){
                mUsefulExpressionsViewModel.getUsefulExpressionsCateList()
            }
        }
    }

    private var onUsefulButtonClick = object : OnUsefulButtonClick {
        override fun onAddButton(content: String, type: Int) {
            super.onAddButton(content, type)
            if (type == USEFUL_OPT_ADD_CATE){
                //添加常用语分组
                showLoading()
                mUsefulExpressionsViewModel.addUsefulExpressionCate(content)
            }else{
                //添加常用语
                mChooseUseCateId?.let {
                    showLoading()
                    mUsefulExpressionsViewModel.addUsefulExpression(it,content)
                }
            }
        }
    }
    override fun initData() {
        super.initData()
        mUsefulExpressionsViewModel.getUsefulExpressionsCateList()
    }

    /**
     * 初始化dsltab
     */
    private fun initDslTab(){
        mViewPagerAdapter = ViewPage2FragmentAdapter(supportFragmentManager, lifecycle, mFragments)
        mBinding.viewpager2.apply {
            offscreenPageLimit = ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT
            orientation = ViewPager2.ORIENTATION_HORIZONTAL
            isUserInputEnabled = false//禁止viewPage滑动
            registerOnPageChangeCallback(viewPager2Callback)
            adapter = mViewPagerAdapter
        }
    }

    /**
     * VIewPager2选择回调
     */
    private val viewPager2Callback = object : ViewPager2.OnPageChangeCallback() {
        override fun onPageSelected(position: Int) {
            if(position == 0){
                //第0个为默认常用语，默认常用语
                mBinding.apply {
                    val bgDrawable = ContextCompat.getDrawable(this@UsefulExpressionsActivity,R.drawable.btn_shape_gray_e3_50)
                    llAddExpression.background = bgDrawable
                    tvAddExpression.setTextColor(  this@UsefulExpressionsActivity.getResources().getColor(R.color.color_999999))
                    llAddExpression.isClickable = false
//                    val bgDrawableAdd = ContextCompat.getDrawable(this@UsefulExpressionsActivity,R.mipmap.ic_useful_add_gray)
//                    ivUsefulAdd.background = bgDrawableAdd
                    ivUsefulAdd.setImageResource(R.mipmap.ic_useful_add_gray)
                }

            }else{
                mBinding.apply {
                    val bgDrawable = ContextCompat.getDrawable(this@UsefulExpressionsActivity,R.drawable.btn_shape_blue_50)
                    llAddExpression.background = bgDrawable
                    tvAddExpression.setTextColor(  this@UsefulExpressionsActivity.getResources().getColor(R.color.white))
                    llAddExpression.isClickable = true
//                    val bgDrawableAdd = ContextCompat.getDrawable(this@UsefulExpressionsActivity,R.mipmap.ic_useful_add)
                    ivUsefulAdd.setImageResource(R.mipmap.ic_useful_add)
                }
            }
        }
    }

}